package cc.lj.internal.coupons.domain.ticket.service.impl.useTicketRule;

import cc.lj.internal.api.ordershare.dto.OrderOnlineAPIDTO;
import cc.lj.internal.api.ordershare.dto.OrderPaymentAPIDTO;
import cc.lj.internal.core.exception.ServiceException;
import cc.lj.internal.coupons.domain.ticket.model.vo.TicketBatchDO;
import cc.lj.internal.coupons.domain.ticket.model.vo.TicketMainDO;
import cc.lj.internal.coupons.domain.ticket.repository.IUseTicketCheckCacheRepository;
import cc.lj.internal.coupons.domain.ticket.service.AbstractUseTicketRuleDomainService;
import cc.lj.internal.coupons.infrastructure.excepion.CoupousExceptionEnum;
import cc.lj.internal.coupons.interfaces.dto.command.UseTicketCheckCommand;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * 用券验证规则 - 满减规则
 * @author liangxifeng
 * @date 2023/6/26 15:12
 */
@Service("useTicketFullReductionRuleDomainServiceImpl")
@Slf4j
public class UseTicketFullReductionRuleDomainServiceImpl extends AbstractUseTicketRuleDomainService {
    //用券验证 redis 缓存仓储接口
    @Resource(name = "usetTicketCheckCacheRedisRepositoryImpl")
    private IUseTicketCheckCacheRepository cacheRepository;

    //查找每个阶梯中的第一张券 工具类
    @Resource(name = "findFirstStepUtil")
    private FindFirstStepUtil findFirstStepUtil;

    @Override
    protected void rule(TicketBatchDO batchDO, TicketMainDO ticketMainDO, UseTicketCheckCommand ticketCheckCommand, OrderOnlineAPIDTO orderOnlineAPIDTO) {
        log.info("【电子券用券验证】：满减规则验证开始==");
        if(ticketCheckCommand.getUuId() == null) throw new ServiceException(CoupousExceptionEnum.USE_TICKET_CHECK_UUID_IS_NULL);
        //1.从redis中读取券批次使用数量 <券批次主键，已用券数量>
        Map<Integer,Integer> usedBatchNumHash = cacheRepository.getUseBatch(ticketCheckCommand.getPactNum(),ticketCheckCommand.getUuId());
        BigDecimal limitValue; //满减剩余空间
        //该合同第一次用券, 满减剩余空间 = 订单应付额
        if( usedBatchNumHash.isEmpty()) {
            //获取订单支付方式数据
            List<OrderPaymentAPIDTO> paymentList = orderOnlineAPIDTO.getOrderPaymentDTOList();
            OrderPaymentAPIDTO orderPaymentAPIDTO = paymentList.get(paymentList.size()-1); //取最后一条数据
            limitValue = orderPaymentAPIDTO.getAccountPayableDiscount();
        }else {
            //缓存中用券其他数据 <single_batch_id: 独立使用的券批次主键, limit_value: 满减剩余额度空间>
            Map<String,Object> useTicketOherData = cacheRepository.getUseTicketOther(ticketCheckCommand.getPactNum(),ticketCheckCommand.getUuId());
            if( useTicketOherData.get("limit_value") == null) throw new ServiceException(CoupousExceptionEnum.REDIS_USE_BATCH_LIMIT_VALUE_IS_NULL);
            limitValue = new BigDecimal( useTicketOherData.get("limit_value").toString() );
        }

        //如果该券是 阶梯中的第一张券，则需要判断 剩余用券额度是否达到券满减条件
        if( findFirstStepUtil.isStepFirstTicket(batchDO,ticketCheckCommand.getPactNum(),ticketCheckCommand.getUuId(),1) ) {
            log.info("用券满减规则：券批次batchId:"+batchDO.getBatchId()+",满减验证规则：已经是阶梯第一张券，满减剩余额度空间="+limitValue+",门槛额度="+batchDO.getConditionValue());
            //如果满多少(门槛额度） > 满减剩余额度空间 && 非蓝景装饰合作， 则此券不可使用
            if( batchDO.getConditionValue().compareTo(limitValue) == 1 && orderOnlineAPIDTO.getDecorationStatus() == 0 ) {
                log.error("用券满减规则：剩余用券额度未达到券满减条件, 券批次batchId:"+batchDO.getBatchId()+",满多少(门槛额度）:"+batchDO.getConditionValue()
                        +"满减剩余额度空间:"+limitValue);
                throw new ServiceException(CoupousExceptionEnum.TICKET_LIMIT_VALUE_ERROR);
            }
        }else {
            log.info("用券满减规则：券批次batchId:"+batchDO.getBatchId()+",满减验证规则：不是阶梯第一张券，满减剩余额度空间="+limitValue+",门槛额度="+batchDO.getConditionValue());
        }
        log.info("【电子券用券验证】：满减规则验证通过==");
    }
}
